﻿using System;
using System.IO;
using System.Data;
using System.Text;
using System.Configuration;
using System.Collections.Generic;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Resources;
using System.Globalization;

using CE.Mail;
using CE.User;
using CE.Global;
using CE.Security;
using CE.InputOut;
using CE.Database;
using CE.CarInsurance;
using CXDecryption;

public partial class carinsurance_ClaimCall : System.Web.UI.Page
{
    private DateTime dateTimeNow = CE.Global.General.GetUTCDateTime();

    protected override void InitializeCulture()
    {
        String selectedCulture = CE.Global.General.SetCulture();
        base.InitializeCulture();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session[CE.Global.General.UserId] == null)
        {
            Response.Redirect("~/SiteUserSecureLogin.aspx");
        }

        if (!IsPostBack)
        {
            ExpiryMonth();
            LoadCarYear();
            LoadCurrentInsurer();

            if (Request.QueryString["mobile"] != null)
            {
                txtMobileNo.Text = Request.QueryString["mobile"].ToString();
            }

            if (Request.QueryString["email"] != null)
            {
                txtEmailAddress.Text = Request.QueryString["email"].ToString();
            }

            if (Request.QueryString["name"] != null)
            {
                txtCustomerName.Text = Request.QueryString["name"].ToString();
            }
        }
    }

    #region ExpiryMonth

    private void ExpiryMonth()
    {
        CultureInfo ci = CultureInfo.CurrentCulture;
        int mthDiff = 12;
        for (int m = 0; m < mthDiff; m++)
        {
            DateTime dtTemp = new DateTime(dateTimeNow.Year, 1 + m, 1);
            string strDate = dtTemp.ToString("MM", new CultureInfo("en-US"));
            ddlExpiryMonth.Items.Add(new ListItem(dtTemp.ToString("MMMM", ci), strDate));
        }
        ddlExpiryMonth.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
    }

    #endregion

    #region Insurer

    public void LoadCurrentInsurer()
    {
        DataTable _dt = null;
        try
        {
            MyDatabase _db = new MyDatabase();

            string _sqlstatement = "";

            if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
            {
                _sqlstatement = _sqlstatement = "SELECT TH AS Name, ClaimInsurerId  FROM tblClaimProviderCompany Where [Status] = 1 Order by TH ";
            }
            else
            {
                _sqlstatement = _sqlstatement = "SELECT EN AS Name, ClaimInsurerId  FROM tblClaimProviderCompany Where [Status] = 1 Order by EN ";
            }

            _dt = _db.GetDataTable(_sqlstatement);

            DataTable dtPreInsurerComp = _dt;
            ddlCurrentInsurer.DataSource = dtPreInsurerComp;
            ddlCurrentInsurer.DataTextField = "Name";
            ddlCurrentInsurer.DataValueField = "ClaimInsurerId";
            ddlCurrentInsurer.DataBind();
            ddlCurrentInsurer.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
        }
        catch (Exception Ex)
        {
        }
    }

    #endregion

    #region Car

    private void LoadCarYear()
    {
        int _yearCount = 10;
        ddlCarYear.Items.Clear();

        int _startYear = dateTimeNow.Year - _yearCount;
        int _endYear = dateTimeNow.Year;
        for (int i = _endYear; i >= _startYear; i--)
        {
            if (HttpContext.Current.Session["Language"].ToString() != "th-TH")
            {
                ddlCarYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
            }
            else
            {
                ddlCarYear.Items.Add(new ListItem(i.ToString() + " - พ.ศ. " + (i + 543).ToString(), i.ToString()));
            }
        }
        ddlCarYear.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
    }

    protected void ddlCarYear_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlCarYear.Text == "-1")
        {
            ClearAllList();
        }
        else
        {
            GetCarMakeList(ddlCarYear.Text, ddlCarMake);
            if (ddlCarMake.Items.Count > 0)
            {
                ddlCarMake.SelectedIndex = 0;
                ddlCarMake_SelectedIndexChanged(sender, e);
            }
        }
    }

    protected void ddlCarMake_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlCarMake.Text == "-1")
        {
            ddlModelBodyCCDoor.Items.Clear();
            ddlModelBodyCCDoor.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
            txtSumInsured.Text = "0";
            lblSumInsured.Text = "0";
            txtGroupNo.Text = "-1";
        }
        else
        {
            GetCarModelDescList(ddlCarMake.Text, ddlCarYear.Text, ddlModelBodyCCDoor);
            if (ddlModelBodyCCDoor.Items.Count > 0)
            {
                ddlModelBodyCCDoor.SelectedIndex = 0;
                ddlModelBodyCCDoor_SelectedIndexChanged(sender, e);
            }
        }
    }

    protected void ddlModelBodyCCDoor_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlCarYear.SelectedIndex >= 0 && ddlCarMake.SelectedIndex >= 0 & ddlModelBodyCCDoor.SelectedIndex >= 0)
        {
            string[] _tempDesc = ddlModelBodyCCDoor.Text.Split(' ');
            string _model = "";
            string _body = "";
            string _cc = "";
            string _door = "";
            if (_tempDesc.Length == 5)
            {
                _model = _tempDesc[0];
                _body = _tempDesc[1];
                _cc = _tempDesc[2].Substring(0, _tempDesc[2].Length - 2);
                _door = _tempDesc[3];
            }
            else if (_tempDesc.Length == 6)
            {
                _model = _tempDesc[0] + " " + _tempDesc[1];
                _body = _tempDesc[2];
                _cc = _tempDesc[3].Substring(0, _tempDesc[3].Length - 2);
                _door = _tempDesc[4];
            }
            else if (_tempDesc.Length == 7)
            {
                _model = _tempDesc[0] + " " + _tempDesc[1] + " " + _tempDesc[2];
                _body = _tempDesc[3];
                _cc = _tempDesc[4].Substring(0, _tempDesc[4].Length - 2);
                _door = _tempDesc[5];
            }
            lblModelDesc.Text = "model : " + _model + ", body: " + _body + ", cc: " + _cc + ", door: " + _door;
            GetCarModelSumInsuredAmountAndVehicleType(ddlCarMake.Text, _model, _body, _cc, _door, ddlCarYear.Text, txtSumInsured, lblSumInsured, lblCarVehicleType);
            txtNewSumInsured.Text = txtSumInsured.Text;
            GetCarModelGroupNo(ddlCarMake.Text, _model, _body, _cc, _door, txtGroupNo);
        }
    }

    private void ClearAllList()
    {
        ddlCarMake.Items.Clear();
        ddlCarMake.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
        ddlModelBodyCCDoor.Items.Clear();
        ddlModelBodyCCDoor.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
        txtSumInsured.Text = "0";
        lblSumInsured.Text = "0";
        txtGroupNo.Text = "-1";
    }

    private void GetCarMakeList(string Year, DropDownList ddlList)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblMake");
        SortedList _spList = new SortedList();
        _spList.Add("@Year", Year);
        _dt = _db.GetDataTableBySP("sprocGetCarMakeTHListByYear", _spList);
        ddlList.Items.Clear();
        ddlList.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
        if (_dt != null && _dt.Rows.Count > 0)
        {
            for (int i = 0; i < _dt.Rows.Count; i++)
            {
                ddlList.Items.Add(new ListItem(_dt.Rows[i][1].ToString(), _dt.Rows[i][0].ToString()));
            }
        }

        _dt = null;
        _db = null;
    }

    private void GetCarModelDescList(string CarMake, string Year, DropDownList ddlList)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblModelDesc");
        SortedList _spList = new SortedList();
        _spList.Add("@CarMake", CarMake);
        _spList.Add("@Year", Year);
        _dt = _db.GetDataTableBySP("sprocKawnaGetCarModelDescListByCarMakeCode", _spList);
        ddlList.Items.Clear();
        ddlModelBodyCCDoor.Items.Clear();
        ddlModelBodyCCDoor.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
        if (_dt != null && _dt.Rows.Count > 0)
        {
            ddlList.DataSource = _dt;
            ddlList.DataTextField = "CarModelDisplay";
            ddlList.DataValueField = "CarModelDesc";
            ddlList.DataBind();
           
        }
        else
        {
            ddlList.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
        }
        _dt = null;
        _db = null;
    }

    private void GetCarModelGroupNo(string CarMake, string CarModel, string Body, string CC, string Door, TextBox txtTextBox)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblModelBody");
        SortedList _spList = new SortedList();
        _spList.Add("@CarMake", CarMake);
        _spList.Add("@CarModel", CarModel);
        _spList.Add("@Body", Body);
        _spList.Add("@CC", CC);
        _spList.Add("@Door", Door);
        _dt = _db.GetDataTableBySP("sprocGetCarModelGroupTH", _spList);

        if (_dt != null && _dt.Rows.Count > 0)
        {
            txtTextBox.Text = _dt.Rows[0][0].ToString();
        }
        else
        {
            txtGroupNo.Text = "-1";
        }
        txtTextBox.ReadOnly = true;
        _dt = null;
        _db = null;
    }

    private void GetCarModelSumInsuredAmountAndVehicleType(string CarMake, string CarModel, string Body, string CC, string Door, string Year, TextBox txtTextBox, Label lblLabel, Label lblLabelTwo)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblModelBody");
        SortedList _spList = new SortedList();
        _spList.Add("@CarMake", CarMake);
        _spList.Add("@CarModel", CarModel);
        _spList.Add("@Body", Body);
        _spList.Add("@CC", CC);
        _spList.Add("@Door", Door);
        _spList.Add("@Year", Year);
        _dt = _db.GetDataTableBySP("sprocGetCarModelSumInsuredAndVehicleTypeTHListByYear", _spList);
        if (_dt != null && _dt.Rows.Count > 0)
        {
            txtTextBox.Text = _dt.Rows[0][0].ToString();
            lblLabelTwo.Text = _dt.Rows[0][1].ToString();
            lblLabel.Text = Convert.ToInt32(txtTextBox.Text).ToString("#,000");
            
        }
        else
        {
            txtTextBox.Text = "0";
            lblLabel.Text = "0";
        }
        txtTextBox.ReadOnly = true;
        _dt = null;
        _db = null;
    }

    #endregion

    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/carinsurance/ViewCICustomerCallNewSearch.aspx?calltype=103");
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        Page.Validate("newleads");
        if (Page.IsValid)
        {
            Int64 _userId = 0;

            if (!Int64.TryParse(txtCustomerId.Text, out _userId))
            {
                _userId = 0;
            }

            if (_userId == 0)
            {
                CarUserAccount _userAccount = GetCustomerAccount();

                if (_userAccount != null && _userAccount.CEID > 0)
                {
                    txtCustomerId.Text = _userAccount.CEID.ToString();
                    lblRedirectCustomerId.Text = _userAccount.CEID.ToString();

                    _userId = _userAccount.CEID;
                }
            }

            _userId = UpdateProfile(_userId);

            if (_userId > 0)
            {
                if (SaveCRM(_userId))
                {
                    if (SaveClaim())
                    {
                        lblMessage.Text = "Saved successfully!";
                        Response.Redirect("~/carinsurance/ViewCICustomerCallNewSearch.aspx?calltype=103");
                    }
                    else
                    {
                        lblMessage.Text = "Saving did NOT succeed!";
                    }
                }
                else
                {
                    lblMessage.Text = "Saving did NOT succeed!";
                }
            }
            else
            {
                lblMessage.Text = "Saving did NOT succeed!";
            }
        }
    }

    #region Save & Update

    private bool SaveClaim()
    {
        Int64 _claimresult = 0;
        Claim _claim = new Claim();
        ClaimDB _claimdb = new ClaimDB();

        _claim.ManufactYear = Convert.ToInt32(ddlCarYear.Text);

        _claim.CarMakeName = ddlCarMake.Text;//Convert.ToInt32(txtCarMakeId.Text);

        string[] _tempDesc = ddlModelBodyCCDoor.Text.Split(' ');
        if (_tempDesc.Length == 5)
        {
            _claim.CarModelName = _tempDesc[0];
            _claim.Body = _tempDesc[1];
            _claim.CC = Convert.ToInt32(_tempDesc[2].Substring(0, _tempDesc[2].Length - 2));
            _claim.Door = Convert.ToInt32(_tempDesc[3]);
        }
        else if (_tempDesc.Length == 6)
        {
            _claim.CarModelName = _tempDesc[0] + " " + _tempDesc[1];
            _claim.Body = _tempDesc[2];
            _claim.CC = Convert.ToInt32(_tempDesc[3].Substring(0, _tempDesc[3].Length - 2));
            _claim.Door = Convert.ToInt32(_tempDesc[4]);
        }
        else if (_tempDesc.Length == 7)
        {
            _claim.CarModelName = _tempDesc[0] + " " + _tempDesc[1] + " " + _tempDesc[2];
            _claim.Body = _tempDesc[3];
            _claim.CC = Convert.ToInt32(_tempDesc[4].Substring(0, _tempDesc[4].Length - 2));
            _claim.Door = Convert.ToInt32(_tempDesc[5]);
        }
        _claim.GroupNo = Convert.ToInt32(txtGroupNo.Text);
        
        _claim.MakeModelDesc = ddlCarMake.SelectedItem.Text + " " + ddlModelBodyCCDoor.SelectedItem.Text;
        _claim.AgentId = Convert.ToInt64(Session[General.UserId]);

        _claim.Name = txtCustomerName.Text.Trim();
        _claim.Email = txtEmailAddress.Text.Trim();
        _claim.Phone = txtMobileNo.Text.Trim();
        _claim.ClaimInsurerId = Convert.ToInt32(ddlCurrentInsurer.SelectedValue);
        _claim.ExpiryMonth = ddlExpiryMonth.SelectedValue;

        _claimresult = _claimdb.Insert(_claim);
        _claim = null;
        _claimdb = null;

        if (_claimresult == -1)
        {
            //lblMessage.Text = "Insert error!";
            return false;
        }
        return true;
    }

    private bool SaveCRM(Int64 UserID)
    {
        Int64 _carresult = 0;
        Int64 _policyresult = 0;

        CarDetailTH _car = new CarDetailTH();
        CarDetailTHDB _cardb = new CarDetailTHDB();

        CarUserProfileDB _profiledb = new CarUserProfileDB();
        CarUserProfile _profile = new CarUserProfile();

        CarUserContact _contact = new CarUserContact();
        CarUserContactDB _contactdb = new CarUserContactDB();

        _car.Info4 = "NEW";

        if (UserID > 0)
        {
            _profile = _profiledb.GetProfile(UserID);
            _contact = _contactdb.GetContact(UserID);
            if (_profile != null && _contact != null)
            {
                _car.Info5 = _contact.Email;
                _car.Info6 = _contact.Mobile;
                _car.Info7 = _profile.SurName;
                if (_profile.FirstName.Trim().Length > 0)
                {
                    _car.Info8 = _profile.FirstName;//txtFirstName.Text.Trim();
                }
                _car.Info9 = _profile.Gender.ToString(); //ddlGender.GetGender();
                _car.Info10 = _profile.DOB.ToString("dd-MMM-yyyy"); //usrDOB.GetDate().ToString("dd-MMM-yyyy");
                _car.Info11 = _profile.Occupation.ToString();// ddlOccupation.GetOccupation();
                _car.Info12 = _profile.JobNature;//ddlJobNature.GetJobNature();
                _car.Info13 = _profile.MaritalStatus.ToString();//ddlMaritalStatus.GetMaritalStatus();
                _car.Info14 = "0"; //ddlYearDriveSg.Text;
                _car.Info15 = _profile.Salutation;//ddlSalutation.GetSalutation();
                _profile = null;
                _contact = null;
            }
        }

        _car.ManufactYear = Convert.ToInt32(ddlCarYear.Text);

        if (Session[General.UserId] != "0")
        {
            _car.Info2 = Session[General.UserId].ToString();
            _car.Info3 = dateTimeNow.ToString();
        }

        _car.CarMakeName = ddlCarMake.Text;//Convert.ToInt32(txtCarMakeId.Text);

        string[] _tempDesc = ddlModelBodyCCDoor.Text.Split(' ');
        if (_tempDesc.Length == 5)
        {
            _car.CarModelName = _tempDesc[0];
            _car.Body = _tempDesc[1];
            _car.CC = Convert.ToInt32(_tempDesc[2].Substring(0, _tempDesc[2].Length - 2));
            _car.Door = Convert.ToInt32(_tempDesc[3]);
        }
        else if (_tempDesc.Length == 6)
        {
            _car.CarModelName = _tempDesc[0] + " " + _tempDesc[1];
            _car.Body = _tempDesc[2];
            _car.CC = Convert.ToInt32(_tempDesc[3].Substring(0, _tempDesc[3].Length - 2));
            _car.Door = Convert.ToInt32(_tempDesc[4]);
        }
        else if (_tempDesc.Length == 7)
        {
            _car.CarModelName = _tempDesc[0] + " " + _tempDesc[1] + " " + _tempDesc[2];
            _car.Body = _tempDesc[3];
            _car.CC = Convert.ToInt32(_tempDesc[4].Substring(0, _tempDesc[4].Length - 2));
            _car.Door = Convert.ToInt32(_tempDesc[5]);
        }
        _car.GroupNo = Convert.ToInt32(txtGroupNo.Text);
        _car.Info2 = lblCarVehicleType.Text;

        if (lblCarVehicleType.Text == "PS" || lblCarVehicleType.Text == "SV" || lblCarVehicleType.Text == "")
        {
            _car.Info3 = "110";
        }
        else if (lblCarVehicleType.Text == "LC")
        {
            _car.Info3 = "210";
        }
        else if (lblCarVehicleType.Text == "PU")
        {
            _car.Info3 = "320";
        }
       
        _car.MakeModelDesc = ddlCarMake.SelectedItem.Text + " " + ddlModelBodyCCDoor.SelectedItem.Text;
        _car.Status = true;
        _car.RefCEUserId = UserID;
        _car.ViewedDetailId = 0;// Convert.ToInt64(Session[General.ViewedDetailsId].ToString());
        _car.CurrentStep = 1;
        _car.TotalStep = 4;
        if (txtInsurerID.Text.Trim() != "")
        {
            _car.Info1 = txtInsurerID.Text; //ddlCurrentInsurer.Text; //Current Insurer ID
        }
        else
        {
            _car.Info1 = "150";
        }
        _carresult = _cardb.Insert(_car);

        _car = null;
        _cardb = null;
        

        if (_carresult <= 0)
        {
            lblMessage.Text = "Insert error!";
        }

        if (_carresult > 0)
        {
            //CAR POLICY DETAILS
            CarPolicy _carpolicy = new CarPolicy();
            CarPolicyDB _carpolicydb = new CarPolicyDB();
            Int64 _carId = _carresult;

            _carpolicy.Info4 = "NEW";
            _carpolicy.Info8 = "CLAIM";

            lblMessage.Text = "";
            if (Session[General.UserId] != null)
            {
                _carpolicy.Info2 = Session[General.UserId].ToString();
                _carpolicy.Info3 = dateTimeNow.ToString();
            }

            _carpolicy.CECarId = _carId;
            _carpolicy.InsuranceType = 10; //Convert.ToInt32(ddlInsuranceType.Text);
            _carpolicy.GarageType = Convert.ToInt32("1");
            _carpolicy.VehicleType = Convert.ToInt32("110");
            _carpolicy.SumInsured = Convert.ToInt32(txtSumInsured.Text);
            _carpolicy.ProvinceRegistration = "BKK"; //ddlProvinceRegistration.Text;
            _carpolicy.UseOfVehicle = "N/A";//ddlUseOfVehicle.Text;
            string strDate = ddlExpiryMonth.Text;
            int _iMonth = Convert.ToInt32(strDate);
            if (_iMonth <= General.GetUTCDateTimeToday().Month) //DateTime.Today.Month
            {
                _carpolicy.CoverageCommenceDate = new DateTime(General.GetUTCDateTimeToday().AddYears(1).Year, _iMonth, 1); //DateTime.Today.AddYears(1).Year
            }
            else
            {
                _carpolicy.CoverageCommenceDate = new DateTime(General.GetUTCDateTimeToday().Year, _iMonth, 1); //DateTime.Today.Year
            }
            _carpolicy.IsRedPlate = false; //rdoYesRedPlate.Checked;

            _carpolicy.IsAddAccMod = false;
            _carpolicy.AddAccModAmount = 0;
            _carpolicy.NCDPercent = Convert.ToInt32("20");
            _carpolicy.IsClaimLastYear = true;
            _carpolicy.IsCTPL = false;

            _carpolicy.IsAddDriver = false;
            _carpolicy.NoOfDriver = 0;
            //_carpolicy.Deductible = 0;
            _carpolicy.Deductible = Convert.ToInt16("-1");
            if(txtInsurerID.Text.Trim() != "")
            {
                _carpolicy.CurrentInsurer = ddlCurrentInsurer.SelectedItem.Text;
            }
            else
            {
                _carpolicy.CurrentInsurer = Resources.CarInsurance.Other;
            }
            _carpolicy.RefCEUserId = UserID;
            
            _carpolicy.Status = true;
            _carpolicy.CurrentStep = 2;

            //This is for GG Web
            _carpolicy.NInfo5 = 1;

            _policyresult = _carpolicydb.Insert(_carpolicy);
            if (_policyresult > 0)
            {
                txtCECarPolicyId.Text = _policyresult.ToString();

                lblMessage.Text += "<br>Car policy saved successfully!";
                lblMessage.ForeColor = System.Drawing.Color.Blue;
            }
            else
            {
                lblMessage.Text = "Car policy did not save successfully!";
                lblMessage.ForeColor = System.Drawing.Color.Red;
                return false;
            }

            CarDriver _cardriver = new CarDriver();
            CarDriverDB _cardriverdb = new CarDriverDB();
            _cardriverdb.UpdateAllStatus(_carId, UserID);

            _carpolicy = null;
            _carpolicydb = null;
        }

        return _policyresult > 0;
    }

    private Int64 UpdateProfile(Int64 UserId)
    {
        Int64 _retValue = 0;
        CarUserAccount _account = null;
        CarUserAccountDB _accountdb = null;
        CarUserProfile _profile = null;
        CarUserProfileDB _profiledb = null;
        CarUserContact _contact = null;
        CarUserContactDB _contactdb = null;
        if (UserId != 0)
        {
            _account = new CarUserAccount();
            _accountdb = new CarUserAccountDB();

            _profile = new CarUserProfile();
            _profiledb = new CarUserProfileDB();

            _contact = new CarUserContact();
            _contactdb = new CarUserContactDB();

            _account = _accountdb.GetAccount(UserId);
            _profile = _profiledb.GetProfile(UserId);
            _contact = _contactdb.GetContact(UserId);

            if (_account != null)
            {
                if (_account.UserTypeId == 1001)
                {
                    _account.Email = txtEmailAddress.Text;
                    _account.AuthCode = txtMobileNo.Text;
                    _account.RefCEUserID = Convert.ToInt64(txtAgentId.Text);
                    _account.Status = true;
                    _retValue = _accountdb.Insert(_account);
                }
                else
                {
                    _retValue = _account.CEID;
                }
            }

            if (_retValue > 0 && _profile != null)
            {
                #region Update Profile

                _profile.Salutation = ""; // ddlSalutation.GetSalutation();
                _profile.FirstName = txtCustomerName.Text;
                _profile.SurName = "";
                DateTime _dtDOB = new DateTime(1995, 1, 1);
                _profile.DOB = _dtDOB;
                _profile.Gender = 'M';

                _profile.MaritalStatus = -1;// Convert.ToInt32(ddlMaritalStatus.GetMaritalStatus());
                _profile.JobNature = "";// ddlJobNature.GetJobNature();
                _profile.Occupation = Convert.ToInt32("54");
                _profile.YearDriveSg = 0;//Convert.ToInt16(ddlYearDriveSg.Text);
                _profile.Status = "Complete";

                _retValue = _profiledb.Insert(_profile);

                if (_retValue > 0 && _contact != null)
                {
                    if (_account.UserTypeId == 1001)
                    {
                        _contact.Email = txtEmailAddress.Text;
                    }
                    _contact.Mobile = txtMobileNo.Text;
                    _contact.Status = true;

                    _retValue = _contactdb.Insert(_contact);
                }
                else
                {
                    _retValue = 0;
                }

                if (_retValue > 0)
                {
                    _retValue = UserId;
                }
                else
                {
                    _retValue = 0;
                }

                _profile = null;
                _contact = null;
                #endregion
            }
        }
        else
        {
            _retValue = SaveNewCustomer();
            UserId = _retValue;
        }

        return _retValue;
    }

    private Int64 SaveNewCustomer()
    {
        #region New Customer
        Int64 _retVal = 0;


        CarUserAccount _useraccount = new CarUserAccount();
        CarUserAccountDB _useraccountdb = new CarUserAccountDB();

        CarUserProfile _userprofile = new CarUserProfile();
        CarUserProfileDB _userprofiledb = new CarUserProfileDB();
        CarUserContact _contact = new CarUserContact();
        CarUserContactDB _contactdb = new CarUserContactDB();

        long _result = -1;
        _useraccount.Email = txtEmailAddress.Text.ToLower();
        string _authcode = txtMobileNo.Text;

        _useraccount.AuthCode = _authcode;
        _useraccount.UserId = "CEUSERIDBYAGENT";
        _useraccount.UserTypeId = Convert.ToInt32(CE.Global.CEUserType.Customer);
        if (Session[General.UserCampaign] != null && Session[General.UserCampaign].ToString() == "1001")
        {
            _useraccount.UserTypeId = 1001;// Convert.ToInt32(Session[General.UserCampaign].ToString()); 
        }
        _useraccount.IsAcceptTC = false;
        _useraccount.Status = true;
        _useraccount.RefCEUserID = Convert.ToInt64(Session[General.UserId].ToString());
        _result = _useraccountdb.Insert(_useraccount);
        _useraccount.CEID = _result;
        _retVal = _useraccount.CEID;

        if (_result > 0)
        {
            txtCustomerId.Text = _result.ToString();
            lblRedirectCustomerId.Text = txtCustomerId.Text;
            _userprofile.Salutation = ""; //ddlSalutation.GetSalutation();
            _userprofile.FirstName = Server.HtmlEncode(txtCustomerName.Text);
            _userprofile.SurName = "";

            DateTime _dtDOB = new DateTime(1995, 1, 1);
            _userprofile.DOB = _dtDOB;
            _userprofile.Gender = 'M';
            _userprofile.Occupation = Convert.ToInt32("54");
            _userprofile.Status = "Complete";
            _userprofile.RefCEUserId = Convert.ToInt64(txtCustomerId.Text);
            _userprofile.IsAcceptTC = true;
            _result = _userprofiledb.Insert(_userprofile);

            _contact.Email = _useraccount.Email;
            _contact.Mobile = txtMobileNo.Text;
            _contact.Status = true;
            _contact.RefCEUserId = _useraccount.CEID;
            _result = _contactdb.Insert(_contact);
        }

        return _retVal;

        #endregion
    }

    private CarUserAccount GetCustomerAccount()
    {
        CarUserAccount _caruseraccount = new CarUserAccount();
        CarUserAccountDB _caruseraccountdb = new CarUserAccountDB();
        _caruseraccount = _caruseraccountdb.GetUserAccount(txtEmailAddress.Text.Trim(), Convert.ToInt32(CE.Global.CEUserType.Customer));

        return _caruseraccount;
    }

    #endregion

    protected void ddlCurrentInsurer_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            lblClaimInsurerName.Text = "";
            lblClaimHotline.Text = "";
            linkWebsite.Text = "";
            linkWebsite.NavigateUrl = "";
            linkGarageLink.Text = "";
            linkGarageLink.NavigateUrl = "";
            txtInsurerID.Text = "";

            DataTable _dt = null;
            MyDatabase _db = new MyDatabase();

            string _sqlstatement = "";

            if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
            {
                _sqlstatement = _sqlstatement = "SELECT TH AS Name, ClaimInsurerId, PhoneNo1, URL1, URL2, PreInsurerId  FROM tblClaimProviderCompany Where [Status] = 1 AND ClaimInsurerId=" + ddlCurrentInsurer.SelectedValue + " Order by TH ";
            }
            else
            {
                _sqlstatement = _sqlstatement = "SELECT EN AS Name, ClaimInsurerId, PhoneNo1, URL1, URL2, PreInsurerId  FROM tblClaimProviderCompany Where [Status] = 1 AND ClaimInsurerId=" + ddlCurrentInsurer.SelectedValue + " Order by EN ";
            }

            _dt = _db.GetDataTable(_sqlstatement);
            if (_dt.Rows.Count > 0)
            {
                DataRow _dr = _dt.Rows[0];
                lblClaimInsurerName.Text = _dr["Name"].ToString();
                lblClaimHotline.Text = _dr["PhoneNo1"].ToString();
                linkWebsite.Text = _dr["URL1"].ToString();
                linkWebsite.NavigateUrl = _dr["URL1"].ToString();
                linkGarageLink.Text = _dr["URL2"].ToString();
                linkGarageLink.NavigateUrl = _dr["URL2"].ToString();
                if (_dr["PreInsurerId"] != null)
                    txtInsurerID.Text = _dr["PreInsurerId"].ToString();
            }
        }
        catch (Exception)
        {
        }
    }
}
